from fastmcp import FastMCP
import requests

mcp = FastMCP()


@mcp.tool
def fetch_body_fat_rate(height_cm: float, weight_kg: float, age: int, gender: str) -> float:
    """
    体脂率估算工具
    """
    bmi = weight_kg / ((height_cm / 100) ** 2)
    if gender.lower() in ["male", "男", "m"]:
        fat_rate = 1.20 * bmi + 0.23 * age - 16.2
    else:
        fat_rate = 1.20 * bmi + 0.23 * age - 5.4
    return round(fat_rate, 2)


@mcp.tool
def get_weather_info(city: str) -> str:
    """
     获取当前天气信息
     """
    url = f"http://gfeljm.tianqiapi.com/api?unescape=1&version=v63&appid=77614222&appsecret=HJI53FLT&city={city}"

    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        data = response.json()
        return str(data)
    except Exception as e:
        return f"获取天气预警信息失败: {e}"


@mcp.tool
def get_weather_alerts(city: str) -> str:
    """
    获取当前天气预警信息
    """
    url = f"http://gfeljm.tianqiapi.com/api?unescape=1&version=v63&appid=77614222&appsecret=HJI53FLT&city={city}"
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        data = response.json()
        alerts = data.get("alarm", [])
        if alerts:
            # 如果有多个预警，拼接所有预警信息
            alert_msgs = []
            for alert in alerts:
                # 预警内容结构不确定，通常有 title、content、level 等字段
                # 这里做通用处理
                if isinstance(alert, dict):
                    msg = alert.get("title") or alert.get(
                        "content") or str(alert)
                else:
                    msg = str(alert)
                alert_msgs.append(msg)
            return "；".join(alert_msgs)
        else:
            return "当前无天气预警"
    except Exception as e:
        return f"获取天气预警信息失败: {e}"


if __name__ == "__main__":
    mcp.run(transport="http", host="0.0.0.0", port=8000)
